let $ = layui.$;
export default class Theater {
    constructor() {
        this.render()
        this.handel()
    }
    render() {
        let template = `
        <!-- 查询表单 -->
        <h1 style="padding: 15px;">电影院线匹配</h1>
        <form class="layui-form layui-form-pane" id="searchForm" lay-filter="searchForm" style="padding: 10px;">
            <div class="layui-form-item">
                <div class="layui-input-inline">
                    <button class="layui-btn" id="AddfilmAndCinemabtn">新增关联</button>
                </div>
                <div class="layui-input-inline">
                    <select name="type" lay-verify="">
                        <option value="">全部</option>
                        <option value="cinema">影院</option>
                        <option value="film">电影</option>
                    </select>
                </div>
                <div class="layui-input-inline">
                    <input type="text" name="value"
                    placeholder="请输入查询条件" 
                    autocomplete="off"
                    class="layui-input">
                </div>
                <div class="layui-btn-container">
                    <button type="button" class="layui-btn layui-btn-primary" id="searchBtn">查询</button>
                </div>
            </div>
        </form>
        <!-- 渲染表格 -->
        <table id="filmAndCinemaTable" lay-filter="filmAndCinemaTable"></table>
        <!-- 表格里的按钮 -->
        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-xs" lay-event="edit">排片管理</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除关联</a>
        </script>
        `
        $('#content').html(template)
    };
    handel() {
        let form = layui.form;
        let table = layui.table;
        let laydate = layui.laydate;
        form.render()
        // 执行渲染
        table.render({
            elem: '#filmAndCinemaTable'
            , url: '/api/filmAndCinemas/'
            , page: {
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
                , limits: [2, 5, 8, 10, 15]
                , limit: 5
            }
            , cols: [[ // 标题栏
                { checkbox: true }
                , {
                    field: 'cinema', title: '影院', templet: function (d) {
                        return d.cinema ? d.cinema.name : "影院已被移除"
                    }
                }
                , {
                    field: 'film', title: '电影', templet: function (d) {
                        return d.film ? d.film.name : "电影已被移除"
                    }
                }
                // , { field: '_id', title: 'id', hide: true } // 不需要，可以直接获取 id 的
                , { fixed: 'right', title: '操作', toolbar: '#barDemo' }
            ]]
            , request: {
                pageName: 'current' // 页码的参数名称，默认：page
                , limitName: 'size' // 每页数据量的参数名，默认：limit
            }
            , parseData: function (res) { // res 即为原始返回的数据
                return {
                    "code": 0, // 解析接口状态
                    "msg": '', // 解析提示文本
                    "count": res.total, // 解析数据长度
                    "data": res.rows // 解析数据列表
                };
            }
        });

        // -----------------查询事件-----------------
        $('#searchBtn').click(function () {
            console.log(form.val('searchForm'));
            if (form.val('searchForm').type == 'cinema') {
                console.log('cinema');
                $.ajax({
                    type: 'get',
                    url: '/api/cinemas/',
                    data: {
                        opt: 'name',
                        text: form.val('searchForm').value,
                        flag: 'true'
                    },
                    success(res) {
                        console.log(11111);
                        console.log(res.rows);
                        if (res.rows.length > 0) {
                            console.log(res.rows[0]);
                            let cinemaId = res.rows[0]._id;
                            table.reload('filmAndCinemaTable', {
                                where: {
                                    type: 'cinema',
                                    value: cinemaId,
                                } //设定异步数据接口的额外参数
                                , page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            });
                        } else {
                            layer.msg('无查询结果', { icon: 2 });
                        }

                    }
                })
            } else if (form.val('searchForm').type == 'film') {
                console.log('film');
                $.ajax({
                    type: 'get',
                    url: '/api/films/',
                    data: {
                        type: 'name',
                        value: form.val('searchForm').value,
                        flag: 'true'
                    },
                    success(res) {
                        console.log(res.rows);
                        if (res.rows.length > 0) {
                            console.log(res.rows[0]);
                            let filmId = res.rows[0]._id;
                            table.reload('filmAndCinemaTable', {
                                where: {
                                    type: 'film',
                                    value: filmId,
                                } //设定异步数据接口的额外参数
                                , page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            });
                        } else {
                            layer.msg('无查询结果', { icon: 2 });
                        }

                    }
                })
            } else {
                table.reload('filmAndCinemaTable', {
                    where: {
                        type: '',
                    } //设定异步数据接口的额外参数
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }

        });

        //监听行工具事件
        table.on('tool(filmAndCinemaTable)', function (obj) {
            var filmAndCinemaData = obj.data; // 行内表格信息
            // -----------------删除关联-----------------
            if (obj.event === 'del') {
                layer.confirm('是否删除该关联', function (index) {
                    $.ajax({
                        type: 'delete',
                        url: `/api/filmAndCinemas/${filmAndCinemaData._id}`,
                        success(res) {
                            table.reload('filmAndCinemaTable', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            });
                            obj.del();
                            layer.close(index);
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                // -----------------排片管理弹出层-----------------
                // 模态框内容
                console.log(filmAndCinemaData);
                layer.open({
                    type: 1
                    , title: '排片管理' //不显示标题栏
                    , area: ['1000px', '500px']
                    , shade: 0.8
                    , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    , btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: `
                        <form class="layui-form layui-form-pane" id="searchScheduleForm" lay-filter="searchScheduleForm"
                         style="padding: 10px;">
                            <div class="layui-form-item">
                                <div class="layui-input-inline">
                                    <button class="layui-btn" id="AddRowPieceBtn">新增排片</button>
                                </div>
                                <div class="layui-input-inline">
                                    <select name="type" lay-verify="">
                                        <option value="">全部</option>
                                        <option value="date">日期</option>
                                        <option value="name">放映厅</option>
                                        <option value="time">时间</option>
                                        <option value="price">价格</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <input type="text" name="value"
                                    placeholder="请输入查询条件" 
                                    autocomplete="off"
                                    class="layui-input">
                                </div>
                                <div class="layui-btn-container">
                                    <button type="button" class="layui-btn layui-btn-primary" id="searchScheduleBtn">查询</button>
                                </div>
                            </div>
                        </form>
                        <!-- 渲染表格 -->
                        <table id="RowPieceTable" lay-filter="RowPieceTable"></table>
                        <!-- 表格里的按钮 -->
                        <script type="text/html" id="RowPieceOpt">
                            <a class="layui-btn layui-btn-xs" lay-event="RowPieceUpdate">修改排片</a>
                            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="RowPieceDel">删除排片</a>
                        </script>
                        `
                    , success(res) {
                        form.render(); // 渲染单选框
                        console.log(filmAndCinemaData._id);
                        table.render({
                            elem: '#RowPieceTable'
                            , url: '/api/filmAndCinemas/' + filmAndCinemaData._id
                            // , page: {
                            //     layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                            //     //,curr: 5 //设定初始在第 5 页
                            //     , groups: 5 //只显示 1 个连续页码
                            //     , first: false //不显示首页
                            //     , last: false //不显示尾页
                            //     , limits: [2, 5, 8, 10, 15]
                            //     , limit: 5
                            // }
                            , cols: [[ // 标题栏
                                { checkbox: true }
                                , { field: 'date', title: '日期', sort: true }
                                , { field: 'name', title: '放映厅', sort: true }
                                , { field: 'time', title: '开始时间', sort: true }
                                , { field: 'price', title: '票价', sort: true }
                                // , { field: '_id', title: 'id', hide: true } // 不需要，可以直接获取 id 的
                                , { fixed: 'right', title: '操作', toolbar: '#RowPieceOpt' }
                            ]]
                            // , request: {
                            //     pageName: 'current' // 页码的参数名称，默认：page
                            //     , limitName: 'size' // 每页数据量的参数名，默认：limit
                            // }
                            , parseData: function (res) { // res 即为原始返回的数据
                                return {
                                    "code": 0, // 解析接口状态
                                    "msg": '', // 解析提示文本
                                    "count": res.schedule.length, // 解析数据长度
                                    "data": res.schedule // 解析数据列表
                                };
                            }
                        });

                        let filmAndCinemaId = filmAndCinemaData._id
                        let cinemaId = filmAndCinemaData.cinema._id
                        console.log("cinemaId", cinemaId);
                        // -----------------查询排片-----------------
                        $('#searchScheduleBtn').on('click', function () {
                            console.log(form.val('searchScheduleForm'));
                            table.reload('RowPieceTable', {
                                url: `/api/filmAndCinemas/schedule/${filmAndCinemaId}`
                                , where: form.val('searchScheduleForm')
                            })
                        })

                        //监听行工具事件
                        table.on('tool(RowPieceTable)', function (obj) {
                            var scheduleData = obj.data; // 行内表格信息
                            console.log(scheduleData);
                            // -----------------删除排片 over -----------------
                            if (obj.event === 'RowPieceDel') {
                                layer.confirm('是否删除该关联', function (index) {
                                    $.ajax({
                                        type: 'put',
                                        url: `/api/filmAndCinemas/schedule/${filmAndCinemaId}`,
                                        data: {
                                            oldScheduleJSON: JSON.stringify(scheduleData)
                                        },
                                        success(res) {
                                            table.reload('RowPieceTable');
                                            obj.del();
                                            layer.close(index);
                                        }
                                    });
                                });
                            } else {
                                // -----------------修改排片弹出层-----------------
                                layer.open({
                                    type: 1
                                    , title: '修改排片' //不显示标题栏
                                    , area: 'auto'
                                    , shade: 0.8
                                    , id: 'LAY_layuipro_02' //设定一个id，防止重复弹出
                                    , btn: ['确认', '取消']
                                    , btnAlign: 'c'
                                    , moveType: 1 //拖拽模式，0或者1
                                    , content: `
                                    <form class="layui-form" action="" lay-filter="updateSchedule">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">日期</label>
                                            <div class="layui-input-inline">
                                                <input type="text" class="layui-input"
                                                id="test1" placeholder="请选择日期" name="date">
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">放映厅</label>
                                            <div class="layui-input-inline">
                                                <select name="name" id="updateScheduleName">
                                                </select>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">时间</label>
                                            <div class="layui-input-inline">
                                                <input type="text" class="layui-input" id="test-limit3"
                                                placeholder="请选择时间" name="time">
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">票价</label>
                                            <div class="layui-input-inline">
                                                <input type="text" name="price" required lay-verify="required" 
                                                placeholder="请输入票价" 
                                                autocomplete="off" 
                                                class="layui-input">
                                            </div>
                                        </div>
                                    </form>
                                    `
                                    , yes(index) {
                                        // console.log(form.val('updateSchedule'));
                                        let newObj = {
                                            date: form.val('updateSchedule').date,
                                            name: form.val('updateSchedule').name,
                                            time: form.val('updateSchedule').time,
                                            price: parseInt(form.val('updateSchedule').price),
                                        }
                                        // console.log('newObj', newObj);
                                        // console.log('scheduleData', scheduleData);
                                        $.ajax({
                                            type: 'put',
                                            url: `/api/filmAndCinemas/schedule/${filmAndCinemaId}`,
                                            data: {
                                                oldScheduleJSON: JSON.stringify(scheduleData),
                                                newScheduleJSON: JSON.stringify(newObj)
                                            },
                                            success(res) {
                                                table.reload('RowPieceTable')
                                            }
                                        })
                                        layer.close(index);
                                        // layer.closeAll();
                                    }
                                    , success(res) {
                                        let nowDate = new Date();
                                        let y = nowDate.getFullYear();
                                        let m = nowDate.getMonth() + 1;
                                        let d = nowDate.getDate();
                                        console.log(`${y}-${m}-${d}`);
                                        // 日期
                                        laydate.render({
                                            elem: '#test1'
                                            , min: `${y}-${m}-${d}`
                                        });
                                        // 时间
                                        laydate.render({
                                            elem: '#test-limit3'
                                            , type: 'time'
                                        });
                                        $.ajax({
                                            type: 'get',
                                            url: '/api/cinemas/' + cinemaId,
                                            // async: false,
                                            success(res) {
                                                console.log('res.screens' + res.screens);
                                                let str = '';
                                                for (let item of res.screens) {
                                                    str += `<option value=${item.name}>${item.name}</option>`
                                                }
                                                $('#updateScheduleName').html(str);
                                                form.val('updateSchedule', scheduleData);
                                                form.render(); // 渲染单选框
                                            }
                                        })
                                    }
                                })
                            }
                        })

                        // -----------------新增排片的弹出层-----------------
                        $('#AddRowPieceBtn').on('click', function () {
                            layer.open({
                                type: 1
                                , title: '新增排片' //不显示标题栏
                                , area: 'auto'
                                , shade: 0.8
                                , id: 'LAY_layuipro_03' //设定一个id，防止重复弹出
                                , btn: ['确认', '取消']
                                , btnAlign: 'c'
                                , moveType: 1 //拖拽模式，0或者1
                                , content: `
                                <form class="layui-form" action="" lay-filter="addSchedule">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">日期</label>
                                        <div class="layui-input-inline">
                                            <input type="text" class="layui-input"
                                            id="test1" placeholder="请选择日期" name="date">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">放映厅</label>
                                        <div class="layui-input-inline">
                                            <select name="name" id="addScheduleName">
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">时间</label>
                                        <div class="layui-input-inline">
                                            <input type="text" class="layui-input" id="test-limit3"
                                            placeholder="请选择时间" name="time">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">票价</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="price" required lay-verify="required" 
                                            placeholder="请输入票价" 
                                            autocomplete="off" 
                                            class="layui-input">
                                        </div>
                                    </div>
                                </form>
                                `
                                , yes(index) {
                                    // console.log(form.val('addSchedule'));
                                    let newObj = {
                                        date: form.val('addSchedule').date,
                                        name: form.val('addSchedule').name,
                                        time: form.val('addSchedule').time,
                                        price: parseInt(form.val('addSchedule').price),
                                    }
                                    // console.log('newObj');
                                    // console.log(newObj);
                                    $.ajax({
                                        type: 'put',
                                        url: `/api/filmAndCinemas/schedule/${filmAndCinemaId}`,
                                        data: {
                                            oldScheduleJSON: 'add',
                                            newScheduleJSON: JSON.stringify(newObj)
                                        },
                                        success(res) {
                                            table.reload('RowPieceTable')
                                        }
                                    })
                                    layer.close(index);
                                    // layer.closeAll();
                                }
                                , success(res) {
                                    let nowDate = new Date();
                                    let y = nowDate.getFullYear();
                                    let m = nowDate.getMonth() + 1;
                                    let d = nowDate.getDate();
                                    console.log(`${y}-${m}-${d}`);
                                    // 日期
                                    laydate.render({
                                        elem: '#test1'
                                        , value: new Date()
                                        , min: `${y}-${m}-${d}`
                                    });
                                    // 时间
                                    laydate.render({
                                        elem: '#test-limit3'
                                        , type: 'time'
                                        , value: new Date()
                                    });
                                    $.ajax({
                                        type: 'get',
                                        url: '/api/cinemas/' + cinemaId,
                                        // async: false,
                                        success(res) {
                                            console.log('res.screens');
                                            console.log(res.screens);
                                            let str = '';
                                            for (let item of res.screens) {
                                                str += `<option value=${item.name}>${item.name}</option>`
                                            }
                                            $('#addScheduleName').html(str);
                                            form.render(); // 渲染单选框
                                        }
                                    });
                                }
                            });
                            return false;
                        });

                    }
                })
            }
        });

        // -----------------增加关联的弹出层-----------------
        $('#AddfilmAndCinemabtn').click(function () {
            // new AddfilmAndCinema()
            layer.open({
                type: 1
                , title: '新增关联' //不显示标题栏
                , area: ['450px', '400px']
                , shade: 0.8
                , id: 'LAY_layuipro_04' //设定一个id，防止重复弹出
                , btn: ['确认', '取消']
                , btnAlign: 'c'
                , moveType: 1 //拖拽模式，0或者1
                , content: `
                <form class="layui-form" action="" lay-filter="AddfilmAndCinema">
                    <div class="layui-form-item">
                        <label class="layui-form-label">搜索影院</label>
                        <div class="layui-input-inline">
                            <input type="text" name="cinemaName"
                            placeholder="请输入影院名" 
                            autocomplete="off" 
                            class="layui-input">
                        </div>
                        <button class="layui-btn" id="searchCinemaBtn">查询</button>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">查询结果</label>
                        <div class="layui-input-inline">
                            <select name="cinema" id="cinemaList">
                            </select>
                        </div>
                        <div class="layui-form-mid layui-word-aux" id="searchCinemaBtn">请选择影院</div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">搜索电影</label>
                        <div class="layui-input-inline">
                            <input type="text" name="filmName"
                            placeholder="请输入电影名" 
                            autocomplete="off" 
                            class="layui-input">
                        </div>
                        <button class="layui-btn" id="searchFilmBtn">查询</button>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">查询结果</label>
                        <div class="layui-input-inline">
                            <select name="film" id="filmList">
                            </select>
                        </div>
                        <div class="layui-form-mid layui-word-aux" id="searchCinemaBtn">请选择电影</div>
                    </div>
                </form>
                `
                , yes(index) {
                    if (form.val('AddfilmAndCinema').film && form.val('AddfilmAndCinema').cinema) {
                        $.ajax({
                            type: 'post',
                            url: `/api/filmAndCinemas/`,
                            data: {
                                cinema: form.val('AddfilmAndCinema').cinema,
                                film: form.val('AddfilmAndCinema').film,
                                schedule: []
                            },
                            success(res) {
                                if (res == '关联已存在') {
                                    layer.msg('关联已存在', { icon: 2 });
                                } else {
                                    layer.msg('关联成功', { icon: 1 });
                                }
                                table.reload('filmAndCinemaTable')
                            }
                        })
                    }
                    layer.close(index);
                    // layer.closeAll();
                }
                , success(res) {
                    form.render();
                    // 查询影院
                    $('#searchCinemaBtn').click(function () {
                        console.log(form.val('AddfilmAndCinema').cinemaName);
                        $.ajax({
                            type: 'get',
                            url: '/api/cinemas/',
                            data: {
                                opt: 'name',
                                text: form.val('AddfilmAndCinema').cinemaName,
                                size: 10
                            },
                            success(res) {
                                console.log(res.rows);
                                if (res.rows.length > 0) {
                                    let str = '';
                                    for (let item of res.rows) {
                                        str += `<option value=${item._id}>${item.name}</option>`
                                    }
                                    $('#cinemaList').html(str);
                                } else {
                                    $('#cinemaList').html('<option value="">没有找到相关结果</option>');
                                }
                                form.render();
                            }
                        })
                        return false
                    })

                    // 查询电影
                    $('#searchFilmBtn').click(function () {
                        console.log(form.val('AddfilmAndCinema').filmName);
                        $.ajax({
                            type: 'get',
                            url: '/api/films/',
                            data: {
                                type: 'name',
                                value: form.val('AddfilmAndCinema').filmName,
                                size: 10
                            },
                            success(res) {
                                console.log(res.rows);
                                if (res.rows.length > 0) {
                                    let str = '';
                                    for (let item of res.rows) {
                                        str += `<option value=${item._id}>${item.name}</option>`
                                    }
                                    $('#filmList').html(str);
                                } else {
                                    $('#filmList').html('<option value="">没有找到相关结果</option>');
                                }
                                form.render();
                            }
                        });
                        return false
                    })


                }
            })
            return false;
        });
    }
}